package com.jimo.fl_space

import android.content.pm.ApplicationInfo
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Handler
import android.os.Looper
import com.fvbox.lib.FCore
import com.fvbox.lib.utils.AbiUtils
import com.jimo.fl_space.util.ContextHolder
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.io.ByteArrayOutputStream
import java.io.File
import java.lang.Exception


class SpacePlugin  : MethodCallHandler{
    override fun onMethodCall(call: MethodCall, result: Result) {
        val map: Map<String, Any>? = call.arguments()
        when (call.method) {
            "init" -> {
                getUser()
//                val builder = PackageRule.Builder(
//                    "com.tencent.mm",  /*作用域进程，如果所有进程则留空*/
//                    "com.tencent.mm",
//                    "com.tencent.mm:tools",
//                    "com.tencent.mm:appbrand1",
//                    "com.tencent.mm:appbrand2"
//                ) // 禁用某个Activity
//                    .addBlackActivity("com.tencent.mm.plugin.base.stub.WXEntryActivity") // 禁用某个广播
//                    .addBlackBroadcast("com.tencent.mm.plugin.appbrand.task.AppBrandTaskPreloadReceiver") // 禁用某个服务
//                    .addBlackService("com.tencent.mm.plugin.backup.backuppcmodel.BackupPcService") // 禁用某个ContentProvider
//                    .addBlackContentProvider("androidx.startup.InitializationProvider") // 预加载进程，可预先启动某个进程 加快运行时体验速度。
//                    .addPreloadProcessName("com.tencent.mm:appbrand1") // 禁止某个进程启动
//                    .addBlackProcessName("com.tencent.mm:appbrand2") // 禁止访问某文件
//                    .addBlackIO("/proc/self/maps") // 重定向某文件
//                    .addRedirectIO("/proc/self/cmdline", "/proc/self/fake-cmdline") // 隐藏Root
//                    .isHideRoot(true) // 隐藏Sim
//                    .isHideSim(true) // 隐藏VPN
//                    .isHideVpn(true) // 许多等等....
//                    // 设置环境语言
//                    .setLanguage("zh") // 设置当前所在区域
//                    .setRegion("CN") // 设置当前时区
//                    .setTimeZone("Asia/Shanghai")
//                val build = builder.build()
//
//                // 加入单条规则
//
//                // 加入单条规则
//                FCore.get().addRule(build)
//
//
//                // 如果多条规则请放入FRule
//
//
//                // 如果多条规则请放入FRule
//                val fRule = FRule(builder.build(), builder.build(), builder.build())
//                FCore.get().addFRule(fRule)
//
//
//                // 可云下发配置内容
//
//
//                // 可云下发配置内容
//                val json = Gson().toJson(fRule)
//                // 客户端加载云下发json
//                // 客户端加载云下发json
//                FCore.get().addFRuleContent(json)
                result.success("")
            }
            "getInstalledApplications" -> {
                result.success(getBoxAppList(getUser()))
            }
            "install" -> {
                if(map==null){
                    result.error("0","map==null","map==null")
                    return
                }
                if(!FCore.get().isInstalled(map["pName"]as String, getUser())){
                    FCore.get().installPackageAsUser(map["pName"]as String, getUser())
                }
                result.success("")
            }
            "isInstall" -> {
                if(map==null){
                    result.error("0","map==null","map==null")
                    return
                }
                result.success(FCore.get().isInstalled(map["pName"]as String, getUser()))
            }
            "launchApk" -> {
                if(map==null){
                    result.error("0","map==null","map==null")
                    return
                }
                val handler = Handler(Looper.getMainLooper())
                handler.post {
                    FCore.get().launchApk(map["pName"]as String, getUser())
                }
            }
            "uninstallPackageAsUser" -> {
                if(map==null){
                    result.error("0","map==null","map==null")
                    return
                }
                val handler = Handler(Looper.getMainLooper())
                handler.post {
                    FCore.get().uninstallPackageAsUser(map["pName"]as String, getUser())
                }
                result.success("")
            }
            "getLocalInstallApp" -> {
                result.success(getLocalInstallApp())
            }
            else -> result.notImplemented()
        }
    }
    private fun getBoxAppList(userID: Int): ArrayList<HashMap<String, Any>>? {
        try {
            val appList = arrayListOf<HashMap<String,Any>>()
            FCore.get().apply {
                val list = getInstalledApplications(userID)
                for (app in list) {
                    app.packageInfo ?: continue
                    val applicationInfo = app.packageInfo!!.applicationInfo
                    val name = applicationInfo.loadLabel(packageManager).toString()
                    val icon = applicationInfo.loadIcon(packageManager) as BitmapDrawable
                    val stream = ByteArrayOutputStream()
                    icon.bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
                    appList.add(hashMapOf(
                        "name" to name,
                        "packageName" to applicationInfo.packageName,
                        "icon" to stream.toByteArray(),
                    ))
                }
            }
            return appList
        }catch (e:Exception){
            return null
        }
    }
    private fun getUser(): Int {
        if(FCore.get().users.isEmpty()){
            FCore.get().createUser(0);
        }
        return 0
    }
    fun getLocalInstallApp(): ArrayList<HashMap<String, Any>> {
        val localAppList = arrayListOf<HashMap<String,Any>>()
        val packageManager = ContextHolder.get().packageManager
        val installedApplications = packageManager.getInstalledApplications(0)

        val selfPkg = ContextHolder.get().packageName

        localAppList.clear()

        installedApplications.forEach {

            if (it.packageName == selfPkg) {
                return@forEach
            }

            if ((it.flags and ApplicationInfo.FLAG_SYSTEM) != 0) {
                return@forEach
            }

            val apkFile = File(it.sourceDir)


            val isSupport = AbiUtils.isSupport(apkFile)
            val name = it.loadLabel(packageManager).toString()
            val icon = it.loadIcon(packageManager) as BitmapDrawable
            val stream = ByteArrayOutputStream()
            icon.bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
            localAppList.add(hashMapOf(
                "name" to name,
                "packageName" to it.packageName,
                "icon" to stream.toByteArray(),
                "isSupport" to isSupport
            ))
        }


        localAppList.sortBy { it["name"]as String }
        return localAppList
    }
}